package com.wuwei.jy.Service;

import com.wuwei.jy.dao.ArticleDao;
import com.wuwei.jy.dao.g.ArticleMapper;
import com.wuwei.jy.domain.g.Article;
import com.wuwei.jy.domain.g.ArticleExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ArticleService {
	@Autowired
	private ArticleMapper articleMapper;
	@Autowired
	private ArticleDao articleDao;

	public void addArticle(String title, String content, String img, int type, String endDate, String wechatName, String wechatUrl, int weighNumber){
		Article article = new Article();
		article.setTitle(title);
		article.setContent(content);
		article.setType(type);
		article.setCreateDate(new Date());
		article.setImg(img);

		if (endDate != null && !endDate.equals("")){
			SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd");
			try {
				article.setEndDate(sdf.parse(endDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		article.setWechatName(wechatName);
		article.setWechatUrl(wechatUrl);
		article.setWeigh(weighNumber);
		article.setReadNumber(0);
		article.setGoodNumber(0);
		article.setInuse(1);
		articleMapper.insert(article);
	}

    public List<Article> getArticleList(int start, int limit) {
		ArticleExample articleExample = new ArticleExample();
		articleExample.createCriteria().andInuseEqualTo(1);
		articleExample.setOrderByClause("weigh ASC");
		articleExample.setLimit(start,limit);
		List articleList = articleDao.selectListByExample(articleExample);
        return articleList;
    }

	public long getArticleListCount() {
		ArticleExample articleExample = new ArticleExample();
		articleExample.createCriteria().andInuseEqualTo(1);
		return articleMapper.countByExample(articleExample);
	}

	public void deleteArticle(int id) {
		Article article = articleMapper.selectByPrimaryKey(id);
		article.setInuse(0);
		articleMapper.updateByPrimaryKey(article);
	}

    public Article articleInfo(int id) {
		return articleMapper.selectByPrimaryKey(id);
    }
}
